using GameFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace LS.Event
{
    public class EventSender : IEventSender
    {
        protected GameFrameworkLinkedList<IEventReceiver> m_EventLinkedList = null;

        public EventSender()
        {
            m_EventLinkedList = new GameFrameworkLinkedList<IEventReceiver>();
        }

        public void Fire(object data = null)
        {
            var node = m_EventLinkedList.First;
            while (node != null)
            {
                node.Value.Invoke(data);
            }
        }

        public void Subscribe(IEventReceiver eventReceiver)
        {
            if (m_EventLinkedList == null)
            {
                return;
            }

            if (m_EventLinkedList.Find(eventReceiver) != null)
            {
                throw new LSRuntimeException("Receiver is exist!!");
            }

            var node = m_EventLinkedList.First;
            while (node != null)
            {
                if (node.Value.Priority < eventReceiver.Priority)
                {
                    break;
                }
                else
                {
                    node = node.Next;
                }
            }
            if (node == null)
            {
                m_EventLinkedList.AddLast(eventReceiver);
            }
            else
            {
                m_EventLinkedList.AddBefore(node, eventReceiver);
            }
            
        }

        public void Unsubscribe(IEventReceiver receiver)
        {
            if (m_EventLinkedList == null)
            {
                return;
            }
            m_EventLinkedList.Remove(receiver);
        }
    }
}
